package com.niiwoo.civet.user.service.duboo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.asset.org.business.dto.request.OrgApplyOrderRequestDTO;
import com.niiwoo.asset.org.business.dto.response.*;
import com.niiwoo.asset.org.business.service.dubbo.OrgProjectOrderDubboService;
import com.niiwoo.civet.trade.dto.response.myloan.LoanVoucherAuditInfoQueryResponseDTO;
import com.niiwoo.civet.trade.dto.response.org.AssetOrgProjectResponseDTO;
import com.niiwoo.civet.trade.enums.LoanTypeEnum;
import com.niiwoo.civet.trade.enums.ProjectFromSourceEnum;
import com.niiwoo.civet.trade.enums.TradeConfigEnum;
import com.niiwoo.civet.trade.service.configure.TradeConfigDubboService;
import com.niiwoo.civet.trade.service.org.OrgProjectDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.user.dto.LinkManDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserProfessionDubboInfoDTO;
import com.niiwoo.civet.user.dto.request.LoanUserAuditReportRequestDTO;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.*;
import com.niiwoo.civet.user.enums.UserImgTypeEnum;
import com.niiwoo.civet.user.service.*;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author: wuke
 * @Description:
 * @Date: Created in 13:52 2018/1/23
 */
@Slf4j
@Service(version = "1.0.0")
public class LoanUserDubboServiceImpl implements LoanUserDubboService {
    @Autowired
    PrivacyMasks privacyMasks;

    @Reference(version = "1.0.0")
    private UserDataDubboService userDataDubboService;
//    @Reference(version = "1.0.0")
//    private UserDataSnapshotDubboService userDataSnapshotDubboService;
    @Reference(version = "1.0.0")
    private UserImageFileDubboService userImageFileDubboService;
    @Reference(version = "1.0.0")
    private PortraitAuthDubboService portraitAuthDubboService;
    @Reference(version = "1.0.0")
    private TradeConfigDubboService tradeConfigDubboService;
    @Reference(version = "1.0.0")
    private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;
    @Reference(version = "1.0.0")
    private OrgProjectDubboService orgProjectDubboService;
    @Reference(version = "1.0.0")
    private OrgProjectOrderDubboService orgProjectOrderDubboService;
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;
    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    private static final String NIIWOO_ORG_ID = "00000";  //你我金融的机构ID

    /**
     * 查询借款人审核报告
     * @param requestDTO
     * @return
     */
    public LoanUserAuditReportResponseDTO loanUserAuditReport(LoanUserAuditReportRequestDTO requestDTO){
        LoanUserAuditReportResponseDTO responseDTO = new LoanUserAuditReportResponseDTO();
        String loginUserId = requestDTO.getLoginUserId();
        String borrowUserId = requestDTO.getBorrowUserId();
        Long projectId = requestDTO.getProjectId();
        AssetOrgProjectResponseDTO assetOrgProjectResponseDTO = orgProjectDubboService.getAsserOrgProject(projectId);
        LoanVoucherAuditInfoQueryResponseDTO auditInfoQuery = orgProjectDubboService.loanVoucherAuditInfoQuery(projectId,loginUserId,borrowUserId);
        //普通标的的获取
        if (assetOrgProjectResponseDTO == null){
            UserProfessionDubboInfoDTO userProfessionDubboInfoDTO = userDataDubboService.userProfessionInfo(borrowUserId);
            responseDTO.setOrganizationName("你我金融");
            responseDTO.setImgFileList(this.loanUserImgFile(borrowUserId,projectId));
            responseDTO.setLinkManInfoList(this.loanUserLinkManInfoList(loginUserId,borrowUserId,projectId));
            responseDTO.setZhimaScore(this.loanUserZhimaScore(borrowUserId,projectId));
            this.loanUserProfessionInfo(userProfessionDubboInfoDTO,responseDTO);
        }else{ //机构推送标的信息获取
            OrgApplyOrderRequestDTO orgApplyOrderRequestDTO = new OrgApplyOrderRequestDTO();
            orgApplyOrderRequestDTO.setOrderId(assetOrgProjectResponseDTO.getOrderId());
            orgApplyOrderRequestDTO.setLoanType(auditInfoQuery.getLoanType());
            OrgApplyOrderInfoRespDTO orderInfoRespDTO = orgProjectOrderDubboService.queryOrgApplyReletInfo(orgApplyOrderRequestDTO);

            List<LinkManDubboInfoDTO> linkList = new ArrayList<>();
            List<ImgFileResponseDTO> imgList = new ArrayList<>();
            List<RelatedFileResponstDTO> relatedList = new ArrayList<>();

            List<LinkManDTO> linkManDTOList = orderInfoRespDTO.getLinkManInfoList();
            List<ImgFileDTO> imgFileResponseDTOList = orderInfoRespDTO.getImgFileResponseDTOList();
            List<RelatedFileDTO> housrFileDTOList = orderInfoRespDTO.getHouseFileList();//房产文件
            List<RelatedFileDTO> relationFileList = orderInfoRespDTO.getRelationFileList();//关系证明照文件
            List<RelatedFileDTO> contractFileList = orderInfoRespDTO.getContractFileList();//反担保合同文件
            List<RelatedFileDTO> certificateList = orderInfoRespDTO.getCertificateList();//资质证明图片

            //图片获取
            int size = imgFileResponseDTOList.size();
            for (ImgFileDTO imgFileDTO : imgFileResponseDTOList){
                ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
                imgFileResponseDTO.setImgUrl(imgFileDTO.getImgUrl());
                imgFileResponseDTO.setSubType(this.getImaFileSubTypeByOrgType(imgFileDTO.getSubType(),size));
                imgList.add(imgFileResponseDTO);
            }
            responseDTO.setImgFileList(imgList);
            responseDTO.setCertificateList(this.getRelationFiles(certificateList));

            //联系人获取
            long k = 1;
            for (LinkManDTO linkManDTO : linkManDTOList){
                LinkManDubboInfoDTO linkManDubboInfoDTO = new LinkManDubboInfoDTO();
                linkManDubboInfoDTO.setOrderNo(k);
                linkManDubboInfoDTO.setName(this.maskName(linkManDTO.getName()));
                linkManDubboInfoDTO.setRelation(this.getLinkTypeByOrgType(linkManDTO.getRelation()));
                linkManDubboInfoDTO.setMobileNo(this.maskMobile(privacyMasks.decryptPrivacy(linkManDTO.getMobileNo())));
                linkList.add(linkManDubboInfoDTO);
                k ++ ;
            }

            // 鸿特机构标借款人信息_基本信息中，若为“共借”借款，则不显示房产信息  (是否主借人?0.否;1.是)
            Boolean isShowHouse = auditInfoQuery.getIsMasterBorrower() != null && auditInfoQuery.getIsMasterBorrower().equals(Byte.valueOf("0"));
            //房产  (若借款人本人与房产证户主名称一致，则只展示房产证图片[如果借款本人与房产证户主名称一致，鸿特只传房产证图片])
            if(!isShowHouse){
                responseDTO.setHouseFileList(this.getRelationFiles(housrFileDTOList));
            }
            //若借款人与房产证户主则为配偶关系，则需展示房产图片、关系证明
            if(relationFileList != null && !relationFileList.isEmpty()){
                responseDTO.setRelationFileList(this.getRelationFiles(relationFileList));
                responseDTO.setHouseFileList(this.getRelationFiles(housrFileDTOList));
            }
            //若借款人与房产证户主为其他关系（非配偶关系），则只需展示反担保合同
            if((relationFileList == null || relationFileList.size() == 0) && contractFileList != null && !contractFileList.isEmpty()){
                responseDTO.setHouseFileList(null);
                responseDTO.setRelationFileList(null);
                responseDTO.setContractFileList(this.getRelationFiles(contractFileList));
            }
            //联系人资料
            responseDTO.setLinkManInfoList(linkList);
            //收入情况
            responseDTO.setIncome(orderInfoRespDTO.getIncome());
            //营业执照
            responseDTO.setCharterUrl(orderInfoRespDTO.getCharterUrl());
            //相关资料图片
            responseDTO.setRelatedFileList(relatedList);
            //还款来源
            responseDTO.setRepaymentSource(orderInfoRespDTO.getRepaymentSource());

            if(NIIWOO_ORG_ID.equals(assetOrgProjectResponseDTO.getOrgId())){
                responseDTO.setOrganizationName("你我金融");
            }else {
                SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(assetOrgProjectResponseDTO.getOrgId());
                responseDTO.setOrganizationName(orgInfo.getAbbreviation());
            }

            OrgApplyEShopRespDTO orgApplyEShopRespDTO = orgProjectOrderDubboService.queryApplyEShopInfo(assetOrgProjectResponseDTO.getOrderId());
            if(orgApplyEShopRespDTO != null){
                responseDTO.setCommerceType(orgApplyEShopRespDTO.getEshopType());
                responseDTO.setInternetShopName(orgApplyEShopRespDTO.getEshopName());
                responseDTO.setCommercePlatform(orgApplyEShopRespDTO.getEshopPlatform());
                responseDTO.setManagementModel(orgApplyEShopRespDTO.getEshopBusinessModel());
                responseDTO.setOnlineShopRank(orgApplyEShopRespDTO.getEshopLevel());
                responseDTO.setShopOfficialWebsite(orgApplyEShopRespDTO.getEshopWebsite());
            }
        }

        //授信依据、保障措施
        if(LoanTypeEnum.BUSINESS_LOAN.getValue().equals(auditInfoQuery.getLoanType())){
            responseDTO.setCreditBasis("个人信用保证");
            responseDTO.setSafeguards("个人信用保证");
        }else if(LoanTypeEnum.HOUSE_MORTGAGE_LOAN.getValue().equals(auditInfoQuery.getLoanType())
                || LoanTypeEnum.VEHICLE_MORTGAGE_LOAN.getValue().equals(auditInfoQuery.getLoanType())){
            responseDTO.setCreditBasis("抵押物市值评估" +"\n"+ "个人信用评估");
            responseDTO.setSafeguards("个人信用保证" +"\n"+ "第三方机构担保" +"\n"+ "抵押物处置变现");
        }else {
            responseDTO.setCreditBasis("个人信用评估");
            responseDTO.setSafeguards("个人信用保证" +"\n"+ "第三方机构担保");
        }
        //鸿特机构（房产证供借标）保留
        if (auditInfoQuery.getFromSource() != null && ProjectFromSourceEnum.ORG_SPEEDLOAN_NEW.getType().equals(auditInfoQuery.getFromSource())
                && LoanTypeEnum.OTHER_LOAN.getValue().equals(auditInfoQuery.getLoanType())){
            responseDTO.setCreditBasis("个人信用评估" +"\n"+ "第三人反担保");
            responseDTO.setSafeguards("个人信用保证" +"\n"+ "第三方机构担保" +"\n"+ "第三人反担保");
        }
        // 融360不显示：第三人反担保
        if(auditInfoQuery.getFromSource() != null && ProjectFromSourceEnum.R360.getType().equals(auditInfoQuery.getFromSource())){
            responseDTO.setCreditBasis("个人信用评估");
            responseDTO.setSafeguards("个人信用保证" +"\n"+ "第三方机构担保");
        }
        responseDTO.setProjectType(auditInfoQuery.getType());
        responseDTO.setCaseComplaint("无");  //涉诉情况
        responseDTO.setPunishComplaint("无");     //受行政处罚情况
        responseDTO.setRepaymentAbilityChange("无"); //还款能力变化情况
        responseDTO.setFinancialSituation("良好");  //经营及财务状况
        responseDTO.setRiskResults("因经营不善或失业、疾病、意外等因素导致借款人还款能力下滑，从而发生逾期");
        this.setLoanUserAuditReport(auditInfoQuery, responseDTO);//借款资金运用情况
        return responseDTO;
    }

    /**
     * 获取文件数据
     * @param relatedFileDTOList
     * @return
     */
    private List<RelatedFileResponstDTO> getRelationFiles(List<RelatedFileDTO> relatedFileDTOList){
        List<RelatedFileResponstDTO> relatedList = new ArrayList<RelatedFileResponstDTO>();
        //相关资料获取
        for (RelatedFileDTO relatedFileDTO : relatedFileDTOList){
            RelatedFileResponstDTO fileResponstDTO = new RelatedFileResponstDTO();
            fileResponstDTO.setFileSort(relatedFileDTO.getFileSort());
            fileResponstDTO.setFileUrl(relatedFileDTO.getFileUrl());
            relatedList.add(fileResponstDTO);
        }
        return relatedList;
    }

    /**
     * 查询企业审核报告
     * @param requestDTO
     * @return
     */
    @Override
    public LoanUserAuditReportResponseDTO loanCompanyAuditReport(LoanUserAuditReportRequestDTO requestDTO) {
        LoanUserAuditReportResponseDTO responseDTO = new LoanUserAuditReportResponseDTO();
        String loginUserId = requestDTO.getLoginUserId();
        String borrowUserId = requestDTO.getBorrowUserId();
        Long projectId = requestDTO.getProjectId();
        AssetOrgProjectResponseDTO assetOrgProjectResponseDTO = orgProjectDubboService.getAsserOrgProject(projectId);
        OrgApplyOrderRequestDTO orgApplyOrderRequestDTO = new OrgApplyOrderRequestDTO();
        orgApplyOrderRequestDTO.setOrderId(assetOrgProjectResponseDTO.getOrderId());
        OrgApplyOrderInfoRespDTO orderInfoRespDTO = orgProjectOrderDubboService.queryOrgApplyReletInfo(orgApplyOrderRequestDTO);
        List<LinkManDTO> linkManDTOList = orderInfoRespDTO.getLinkManInfoList();
        List<LinkManDubboInfoDTO> linkList = new ArrayList<LinkManDubboInfoDTO>();
        //qiy
        long k = 1;
        for (LinkManDTO linkManDTO : linkManDTOList){
            LinkManDubboInfoDTO linkManDubboInfoDTO = new LinkManDubboInfoDTO();
            linkManDubboInfoDTO.setMobileNo(this.maskMobile(privacyMasks.decryptPrivacy(linkManDTO.getMobileNo())));
            linkManDubboInfoDTO.setName(this.maskName(linkManDTO.getName()));
            linkManDubboInfoDTO.setRelation(this.getLinkTypeByOrgType(linkManDTO.getRelation()));
            linkManDubboInfoDTO.setOrderNo(k);
            linkList.add(linkManDubboInfoDTO);
            k ++ ;
        }
        responseDTO.setLinkManInfoList(linkList);

        OrgApplyEShopRespDTO orgApplyEShopRespDTO = orgProjectOrderDubboService.queryApplyEShopInfo(assetOrgProjectResponseDTO.getOrderId());
        if(orgApplyEShopRespDTO != null){
            responseDTO.setCommerceType(orgApplyEShopRespDTO.getEshopType());
            responseDTO.setOnlineShopRank(orgApplyEShopRespDTO.getEshopLevel());
            responseDTO.setInternetShopName(orgApplyEShopRespDTO.getEshopName());
            responseDTO.setCommercePlatform(orgApplyEShopRespDTO.getEshopPlatform());
            responseDTO.setShopOfficialWebsite(orgApplyEShopRespDTO.getEshopWebsite());
            responseDTO.setManagementModel(orgApplyEShopRespDTO.getEshopBusinessModel());
        }

        LoanVoucherAuditInfoQueryResponseDTO auditInfoQuery = orgProjectDubboService.loanVoucherAuditInfoQuery(projectId,loginUserId,borrowUserId);
        SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(assetOrgProjectResponseDTO.getOrgId());
        responseDTO.setOrganizationName(orgInfo.getAbbreviation());
        responseDTO.setRepaymentSource(orderInfoRespDTO.getRepaymentSource()); //收入来源
        responseDTO.setIncome(orderInfoRespDTO.getIncome());
        responseDTO.setCharterUrl(orderInfoRespDTO.getCharterUrl()); //企业营业执照URL地址
        responseDTO.setCaseComplaint("无");  //涉诉情况
        responseDTO.setPunishComplaint("无");     //行政处罚情况
        responseDTO.setRepaymentAbilityChange("无"); //还款能力变化情况
        responseDTO.setFinancialSituation("良好");  //经营状况及财务状况
        responseDTO.setCreditBasis("企业信用评估" +"\n"+ "第三人反担保");  //授信依据
        responseDTO.setSafeguards("企业信用保证" +"\n"+ "第三方机构担保" +"\n"+ "第三人反担保");  //保障措施
        responseDTO.setRiskResults("因宏观经济、行情趋势及市场波动、经营不善等因素导致借款人还款能力下滑，从而发生逾期"); //可能产生风险结果
        // 融360不显示：第三人反担保
        if(auditInfoQuery.getFromSource() != null && ProjectFromSourceEnum.R360.getType().equals(auditInfoQuery.getFromSource())){
            responseDTO.setCreditBasis("企业信用评估");
            responseDTO.setSafeguards("企业信用保证" +"\n"+ "第三方机构担保");
        }

        this.setLoanUserAuditReport(auditInfoQuery, responseDTO); //借款资金运用情况
        return responseDTO;
    }

    //借款资金运用情况
    private void setLoanUserAuditReport(LoanVoucherAuditInfoQueryResponseDTO auditInfoQuery,LoanUserAuditReportResponseDTO responseDTO){
        if (auditInfoQuery != null){
            responseDTO.setDebtSituation("未提供"); //负债情况
            responseDTO.setProjectType(auditInfoQuery.getType());
            responseDTO.setCreditTotalAmount(auditInfoQuery.getContractAmount());  //授信总额
            responseDTO.setLoanDesc(auditInfoQuery.getLoanDesc().replaceAll("借款用途：","").replaceAll("借款用于","")); //借款用途

            if(Byte.valueOf("1").equals(auditInfoQuery.getBorrowerType())){
                responseDTO.setOtherInformation("该借款人在本平台借款余额未超过人民币20万元，在不同网络借贷信息中介机构平台借款总余额未超过100万元");
            }else if(Byte.valueOf("2").equals(auditInfoQuery.getBorrowerType())){
                responseDTO.setOtherInformation("该借款人在本平台借款余额未超过人民币100万元，在不同网络借贷信息中介机构平台借款总余额未超过500万元");
            }

            List<LoanVoucherAuditInfoQueryResponseDTO.LoanVoucherAuditImgResponseDTO> loanVoucherImgList = auditInfoQuery.getLoanVoucherImgList();
            if (loanVoucherImgList != null && loanVoucherImgList.size() > 0){
                String imageUrl = loanVoucherImgList.get(0).getImgThumbnailUrl();
                responseDTO.setLoanSnapshotImlUrl(imageUrl);
            }
        }
    }

    //查询借款人信息（收入情况，还款来源）
    private void  loanUserProfessionInfo(UserProfessionDubboInfoDTO professionDubboInfoDTO,LoanUserAuditReportResponseDTO responseDTO){
        if (professionDubboInfoDTO != null){
            //"收入水平: 0-未知，1-2500以下，2-2500-5000，3-5000-8000，4-8000-10000，5-10000-15000，6-15000-25000，7-25000-50000，8-50000以上"
            Byte incomeLevel = professionDubboInfoDTO.getIncomeLevel();
            if (incomeLevel.equals(Byte.valueOf("0"))){
                responseDTO.setIncome("1-2500元以下");
            }else if (incomeLevel.equals(Byte.valueOf("1"))){
                responseDTO.setIncome("2500元以下");
            }else if (incomeLevel.equals(Byte.valueOf("2"))){
                responseDTO.setIncome("2500-5000元");
            }else if (incomeLevel.equals(Byte.valueOf("3"))){
                responseDTO.setIncome("5000-8000元");
            }else if (incomeLevel.equals(Byte.valueOf("4"))){
                responseDTO.setIncome("8000-10000元");
            }else if (incomeLevel.equals(Byte.valueOf("5"))){
                responseDTO.setIncome("10000-15000元");
            }else if (incomeLevel.equals(Byte.valueOf("6"))){
                responseDTO.setIncome("15000-25000元");
            }else if (incomeLevel.equals(Byte.valueOf("7"))){
                responseDTO.setIncome("25000-50000元");
            }else if (incomeLevel.equals(Byte.valueOf("8"))){
                responseDTO.setIncome("50000元以上");
            }
            //收入来源：0-未知，1-工资劳务报酬，2-兼职收入，3-其他收入
            Byte sourceOfIncome = professionDubboInfoDTO.getSourceOfIncome();
            if (sourceOfIncome.equals(Byte.valueOf("0"))){
                responseDTO.setRepaymentSource("其他收入");
            }else if (sourceOfIncome.equals(Byte.valueOf("1"))){
                responseDTO.setRepaymentSource("工资劳务报酬");
            }else if (sourceOfIncome.equals(Byte.valueOf("2"))){
                responseDTO.setRepaymentSource("兼职收入");
            }else if (sourceOfIncome.equals(Byte.valueOf("3"))){
                responseDTO.setRepaymentSource("其他收入");
            }
        }
    }

    //获取借款人联系人信息
    public List<LinkManDubboInfoDTO> loanUserLinkManInfoList(String loginUserId, String borrowUserId, Long projectId){
//        Optional<List<LinkmanInfoSnapshotRespDTO>> linkmanInfoSnapshotRespDTOListOpt = Optional.ofNullable(userDataSnapshotDubboService.linkmanInfoSnapshotQuery(projectId));
//        log.info("loanUserLinkManInfoList.linkmanInfoSnapshotRespDTOListOpt={}",JSON.toJSONString(linkmanInfoSnapshotRespDTOListOpt));
//        return linkmanInfoSnapshotRespDTOListOpt.map(linkmanInfoSnapshotList->{
//            List<LinkManDubboInfoDTO> linkManInfoList = new ArrayList<>();
//            linkmanInfoSnapshotList.forEach(linkmanInfoSnapshot->{
//                LinkManDubboInfoDTO linkManInfoVO = new LinkManDubboInfoDTO();
//                BeanUtils.copyProperties(linkmanInfoSnapshot, linkManInfoVO);
//                if(!Objects.equals(loginUserId,borrowUserId)) {
//                    linkManInfoVO.setMobileNo(privacyMasks.maskMobile(linkManInfoVO.getMobileNo()));
//                    linkManInfoVO.setName(this.maskName(linkManInfoVO.getName()));
//                }
//                linkManInfoList.add(linkManInfoVO);
//            });
//            return linkManInfoList;
//        }).orElseGet(()->{
//            UserPersonalDubboInfoDTO userPersonalDubboInfoDTO = userDataDubboService.userPersonalInfo(borrowUserId);
//            log.info("loanUserLinkManInfoList.userPersonalDubboInfoDTO={}",JSON.toJSONString(userPersonalDubboInfoDTO));
//            if (userPersonalDubboInfoDTO == null) {
//                return null;
//            }
//            List<LinkManDubboInfoDTO> linkManDubboInfoDTOList = userPersonalDubboInfoDTO.getLinkManInfoList();
//            if (!CollectionUtils.isEmpty(linkManDubboInfoDTOList)) {
//                List<LinkManDubboInfoDTO> linkManInfoList = new ArrayList<>();
//                linkManDubboInfoDTOList.forEach(linkManDubboInfoDTO->{
//                    LinkManDubboInfoDTO linkManInfoVO = new LinkManDubboInfoDTO();
//                    BeanUtils.copyProperties(linkManDubboInfoDTO, linkManInfoVO);
//                    if(!Objects.equals(loginUserId,borrowUserId)){
//                        linkManInfoVO.setMobileNo(this.maskMobile(linkManInfoVO.getMobileNo()));
//                        linkManInfoVO.setName(this.maskName(linkManInfoVO.getName()));
//                    }
//                    linkManInfoList.add(linkManInfoVO);
//                });
//                return linkManInfoList;
//            }
//            return null;
//        });
        return new ArrayList<>();
    }

    public String maskMobile(String mobile) {
        if(!StringUtils.hasText(mobile)){
            return null;
        }
        return privacyMasks.maskMobile(mobile);
    }

    public String maskName(String Name) {
        //为空 或者是本人，则不需要打码
        if(!StringUtils.hasText(Name)){
            return Name;
        }
        return Name.substring(0, 1) + "**";
    }

//    private String getHandImageFromSnapshot(ImgFileSnapshotRespDTO imgFileSnapshotRespDTO){
//        String bestLiveImage = userDataSnapshotDubboService.getBestLiveImage(imgFileSnapshotRespDTO.getUserId(),imgFileSnapshotRespDTO.getProjectId());
//        if(StringUtils.hasText(bestLiveImage)){
//            return bestLiveImage;
//        }
//        String releaseUrl = imgFileSnapshotRespDTO.getImgReleaseUrl();
//        return StringUtils.hasText(releaseUrl)?releaseUrl:imgFileSnapshotRespDTO.getImgUrl();
//    }

    /**
     * 根据第三方机构推送的类型映射为统一的用户类型
     * @param orgType
     * @return
     */
    private Byte getImaFileSubTypeByOrgType(Byte orgType,int size){
        Byte subType = new Byte("0");
        if (orgType.byteValue() == 1 && size > 1){
            subType = Byte.valueOf("11");
        }else if (orgType.byteValue() == 2){
            subType = Byte.valueOf("12");
        }else if (orgType.byteValue() == 1 && size == 1){
            subType = Byte.valueOf("14");
        }
        return subType;
    }

    /**
     * 转换为统一的联系人类型（关系：1-配偶，2-父亲，3-母亲，4-兄弟，5-姐妹，6-子女，7-其他 , 8-同事 ，9-朋友）
     * @param orgType
     * @return
     */
    private Byte getLinkTypeByOrgType(Byte orgType){
        Byte subType = new Byte("0");
        if (orgType.byteValue() == 0){
            subType = Byte.valueOf("2");
        }else if (orgType.byteValue() == 1){
            subType = Byte.valueOf("3");
        }else if (orgType.byteValue() == 2){
            subType = Byte.valueOf("4");
        }else if (orgType.byteValue() == 3){
            subType = Byte.valueOf("5");
        }else if (orgType.byteValue() == 4){
            subType = Byte.valueOf("6");
        }else if (orgType.byteValue() == 7){
            subType = Byte.valueOf("7");
        }else if (orgType.byteValue() == 8){
            subType = Byte.valueOf("1");
        }else if (orgType.byteValue() == 5){
            subType = Byte.valueOf("8");
        }else if (orgType.byteValue() == 6){
            subType = Byte.valueOf("9");
        }
        return subType;
    }

    private List<ImgFileResponseDTO> getBestLiveImageFromSnapshot(String userId, Long projectId){
        List<ImgFileResponseDTO> imgFileResponseList = new ArrayList<>();
        String bestLiveImage = "";//userDataSnapshotDubboService.getBestLiveImage(userId,projectId);
        ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
        imgFileResponseDTO.setImgUrl(bestLiveImage);
        imgFileResponseDTO.setSubType(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue());
        imgFileResponseList.add(imgFileResponseDTO);
        return imgFileResponseList;
    }

    private List<ImgFileResponseDTO> loanUserImgFile(String borrowUserId, Long projectId){
        //默认先从标的快照中获取数据
        //如果快照没有，则从实时数据中获取
//        Optional<List<ImgFileSnapshotRespDTO>> imgFileSnapshotRespDTOListOpt = Optional.ofNullable(userDataSnapshotDubboService.imgFileSnapshotQuery(projectId, UserImgSnapshotTypeEnum.IDCARD_IMAGE));
//        log.info("imgFileSnapshotRespDTOListOpt=" + JSON.toJSONString(imgFileSnapshotRespDTOListOpt));
//        return imgFileSnapshotRespDTOListOpt.map(imgFileSnaList->{
//            //List<ImgFileResponseDTO> imgFileResponseList = this.getBestLiveImageFromSnapshot(borrowUserId,projectId);
//
//            ImgFileSnapshotRespDTO handImage = null;
//            List<ImgFileResponseDTO> imgFileResponseList = new ArrayList<>();
//            for(ImgFileSnapshotRespDTO respDTO : imgFileSnaList){
//                ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
//                Byte subType = respDTO.getSubType();
//                imgFileResponseDTO.setSubType(subType);
//                if(UserImgTypeEnum.IDCARD_FRONT_IMAGE.getValue().byteValue() == subType.byteValue()
//                        ||UserImgTypeEnum.IDCARD_BACK_IMAGE.getValue().byteValue() == subType.byteValue()) {
//                    String releaseUrl = respDTO.getImgReleaseUrl();
//                    String imgUrl = StringUtils.hasText(releaseUrl)?releaseUrl:respDTO.getImgUrl();
//                    imgFileResponseDTO.setImgUrl(imgUrl);
//                    imgFileResponseList.add(imgFileResponseDTO);
//                }
//
//                if(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue().byteValue() == subType.byteValue()){
//                    handImage = respDTO;
//                }
//            }
//            this.setBestImageFromSnap(borrowUserId, projectId,handImage,imgFileResponseList);
//            return imgFileResponseList;
//        }).orElseGet(()->{      //从实数数据中获取
//            List<ImgFileResponseDTO> imgFileResponseList = loanUserImgFileFromRealTimeData(borrowUserId);
//            return imgFileResponseList;
//        });
        return new ArrayList<>();
    }

//    private void setBestImageFromSnap(String borrowUserId, Long projectId,ImgFileSnapshotRespDTO handImage,List<ImgFileResponseDTO> imgFileResponseList){
//        String bestLiveImage = userDataSnapshotDubboService.getBestLiveImage(borrowUserId,projectId);
//        if(StringUtils.hasText(bestLiveImage)){
//            ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
//            imgFileResponseDTO.setImgUrl(bestLiveImage);
//            imgFileResponseDTO.setSubType(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue());
//            imgFileResponseList.add(imgFileResponseDTO);
//            return;
//        }
//        if(handImage==null){
//            return;
//        }
//        ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
//        String releaseUrl = handImage.getImgReleaseUrl();
//        String imgUrl = StringUtils.hasText(releaseUrl)?releaseUrl:handImage.getImgUrl();
//        imgFileResponseDTO.setImgUrl(imgUrl);
//        imgFileResponseDTO.setSubType(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue());
//        imgFileResponseList.add(imgFileResponseDTO);
//    }

    private List<ImgFileResponseDTO> loanUserImgFileFromRealTimeData(String borrowUserId){
        Optional<List<UserImageResponseDTO>> imgFileListOpt = Optional.ofNullable(userImageFileDubboService.getImageFileListByType(borrowUserId, UserImgTypeEnum.IDCARD_IMAGE));
        log.info("imgFileListOpt=" + JSON.toJSONString(imgFileListOpt));
        return imgFileListOpt.map(imgFileList->{

            UserImageResponseDTO handImage = null;
            List<ImgFileResponseDTO> imgFileResponseList = new ArrayList<>();
            for(UserImageResponseDTO respDTO : imgFileList){
                ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
                Byte subType = respDTO.getSubType();
                imgFileResponseDTO.setSubType(subType);
                if(UserImgTypeEnum.IDCARD_FRONT_IMAGE.getValue().byteValue() == subType.byteValue()
                        ||UserImgTypeEnum.IDCARD_BACK_IMAGE.getValue().byteValue() == subType.byteValue()) {
                    String releaseUrl = respDTO.getImgReleaseUrl();
                    String imgUrl = StringUtils.hasText(releaseUrl) ? releaseUrl : respDTO.getImgUrl();
                    imgFileResponseDTO.setImgUrl(imgUrl);
                    imgFileResponseList.add(imgFileResponseDTO);
                }

                if(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue().byteValue() == subType.byteValue()){
                    handImage = respDTO;
                }
            }
            this.setBestImageFromRealTime(borrowUserId, handImage, imgFileResponseList);
            return imgFileResponseList;
        }).orElse(null);
    }

    private void setBestImageFromRealTime(String borrowUserId, UserImageResponseDTO handImage, List<ImgFileResponseDTO> imgFileResponseList){
        String bestLiveImage = portraitAuthDubboService.searchBestLiveImage(borrowUserId);
        if(StringUtils.hasText(bestLiveImage)){
            ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
            imgFileResponseDTO.setImgUrl(bestLiveImage);
            imgFileResponseDTO.setSubType(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue());
            imgFileResponseList.add(imgFileResponseDTO);
            return;
        }
        if(handImage==null){
            return;
        }
        ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
        String releaseUrl = handImage.getImgReleaseUrl();
        String imgUrl = StringUtils.hasText(releaseUrl)?releaseUrl:handImage.getImgUrl();
        imgFileResponseDTO.setImgUrl(imgUrl);
        imgFileResponseDTO.setSubType(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue());
        imgFileResponseList.add(imgFileResponseDTO);
    }

    /*private List<ImgFileResponseDTO> getBestLiveImageFromRealTimeData(String userId){
        List<ImgFileResponseDTO> imgFileResponseList = new ArrayList<>();
        String bestLiveImage = portraitAuthDubboService.searchBestLiveImage(userId);
        ImgFileResponseDTO imgFileResponseDTO = new ImgFileResponseDTO();
        imgFileResponseDTO.setImgUrl(bestLiveImage);
        imgFileResponseDTO.setSubType(UserImgTypeEnum.IDCARD_HAND_IMAGE.getValue());
        imgFileResponseList.add(imgFileResponseDTO);
        return imgFileResponseList;
    }*/

    private Integer loanUserZhimaScore(String borrowerUserId,Long projectId){
        Map<String, String> tradeConfigMap = tradeConfigDubboService.selectTradeConfigByEmuns(Arrays.asList(TradeConfigEnum.SESAMEAUTHORIZATIONSTATUS));
        if(tradeConfigMap!=null && "0".equals(tradeConfigMap.get(TradeConfigEnum.SESAMEAUTHORIZATIONSTATUS.getConfigKey()))){
            return null;
        }

        return Optional.ofNullable(this.loanUserZhimaScoreFromSnapshot(borrowerUserId,projectId))
                .map(zhimaScore->zhimaScore)
                .orElseGet(()->this.loanUserZhimaScoreFromRealTimeData(borrowerUserId));
    }

    private Integer loanUserZhimaScoreFromSnapshot(String borrowerUserId,Long projectId){
//        UserInfoSnapshotRespDTO userInfoSnapshotRespDTO = userDataSnapshotDubboService.userInfoSnapshotQuery(borrowerUserId,projectId);
//        return Optional.ofNullable(userInfoSnapshotRespDTO).map(userInfo->userInfo.getZhimaScore()).orElse(null);
        return 1;
    }

    private Integer loanUserZhimaScoreFromRealTimeData(String borrowerUserId){
        UserAuthorizationInfoResponseDTO userAuthorizationInfo = userAuthorizationInfoDubboService.getUserAuthorizationInfo(borrowerUserId);
        return Optional.ofNullable(userAuthorizationInfo).map(userAuth->userAuth.getZhimaScore()).orElse(null);
    }
}
